from django import forms
from app.forms.account import BootstrapForm
from app import models
from django.core.exceptions import ValidationError

class FolderModelForm(BootstrapForm,forms.ModelForm):

    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_obj

    def clean_name(self):
        name = self.cleaned_data['name']
        #判断当前目录下是否文件夹重名
        querrset = models.FileRepository.objects.filter(file_type=2, name=name,project=self.request.tracer.project)
        if not self.parent_obj:
            exist = querrset.filter(parent__isnull=True).exists()
        else:
            exist = querrset.filter(parent=self.parent_obj).exists()
        if exist:
            raise ValidationError('文件夹已存在')
        return name